//
//  LKMessageListViewController.m
//  LKIntelligentVideoProject
//
//  Created by RB8 on 2019/2/27.
//  Copyright © 2019年 she1323. All rights reserved.
//

#import "LKMessageListViewController.h"
#import "LKMessageListCell.h"
#import <MJRefresh.h>
#import "LKMessageDetailViewController.h"
#import "LKSearchBar.h"
@interface LKMessageListViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,assign)NSInteger limit;
@property(nonatomic,strong)LKSearchBar *mySearchBar;
@end

@implementation LKMessageListViewController

-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 50, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - 50 - TAB_BAR_HEIGHT) style:UITableViewStyleGrouped registercellClasss:@[@"LKMessageListCell"]];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSearchView];
    self.page = 1;
    self.limit = 10;
    [self.tableView reloadData];
    [self getDataListWithSearchText:self.mySearchBar.text];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
    self.tableView.mj_footer.hidden = YES;
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"hideKeyBoaderAndCancelButton" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resignSearchBar) name:@"hideKeyBoaderAndCancelButton" object:nil];
    // Do any additional setup after loading the view.
}

/**
 注销键盘的第一反应
 */
-(void)resignSearchBar{
    [self.mySearchBar resignFirstResponder];
    self.mySearchBar.showsCancelButton = NO;
}
-(void)setupSearchView{
    LKSearchBar *searchBar = [[LKSearchBar alloc] init];
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(30);
        make.top.equalTo(self.view.mas_top).offset(10);
        make.width.mas_equalTo(WIDTH );
    }];
    UIButton *cancel = [searchBar valueForKey:@"_cancelButton"];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    //默认提示文字
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.mySearchBar = searchBar;
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.page = 1;
    [self getDataListWithSearchText:self.mySearchBar.text];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.page++;
    [self getDataListWithSearchText:self.mySearchBar.text];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMessageListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMessageListCell"];
    cell.model = self.dataArray[indexPath.section];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000001f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor lightGrayColor];
    return footerView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *unitype;
    switch (self.unitType) {
        case NSUniTypeCover:
            unitype = @"cover";
            break;
        case NSUniTypeVideo:
            unitype = @"video";
            break;
        case NSUniTypeGuard:
            unitype = @"guard";
            break;
        default:
            break;
    }
    NSDictionary *param = @{@"code":unitype,@"roleId":[LKUserInforTool account].roleId};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqual:@"0000"]) {
            LKMessageDetailViewController *vc = [[LKMessageDetailViewController alloc] init];
            vc.model = self.dataArray[indexPath.section];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
/**
 获取数据
 */
-(void)getDataListWithSearchText:(NSString *)searchText{
    [SVProgressHUD showWithStatus:@"数据加载中..."];
    NSDictionary *param;
    NSString *url;
    if (self.unitType != NSUniTypeCover) {
        url = @"/coverAlarm/server/app/queryPageEquipmentAlarm";
        if ([searchText length] > 0) {
            param = @{@"equipmentType":@(self.unitType),@"roleId":[LKUserInforTool account].roleId,@"limit":@(self.limit),@"page":@(self.page),@"sourceName":searchText};
        }else{
            param = @{@"equipmentType":@(self.unitType),@"roleId":[LKUserInforTool account].roleId,@"limit":@(self.limit),@"page":@(self.page)};
        }
    }else{
        
        url = @"/coverAlarm/server/app/queryCoverAlarmByPages";
        if ([searchText length] > 0) {
            param = @{@"limit":@(self.limit),@"roleId":[LKUserInforTool account].roleId,@"page":@(self.page),@"unitAddr":searchText};
        }else{
            param = @{@"limit":@(self.limit),@"roleId":[LKUserInforTool account].roleId,@"page":@(self.page)};
        }
    }
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:url parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        self.tableView.mj_footer.hidden = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        if ([responseObject[@"code"] isEqual:@"0000"]) {
            NSString *count = responseObject[@"count"];
            if (self.page == 1) {
                [self.dataArray removeAllObjects];
            }
            for (NSDictionary *dic in responseObject[@"data"]) {
                LKMessageListModel *model = [LKMessageListModel modelWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            if ([count integerValue] == self.dataArray.count) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            if ([count integerValue] == 0) {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showWithStatus:responseObject[@"msg"]];
        }

    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
            NSLog(@"SearchButton");
            self.page = 1;
            [self getDataListWithSearchText:searchBar.text];
            [searchBar resignFirstResponder];
            searchBar.showsCancelButton = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
    UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"]; //首先取出cancelBtn
    cancelBtn.enabled = YES; //把enabled设置为yes
    self.page = 1;
    [self getDataListWithSearchText:searchBar.text];
    [searchBar resignFirstResponder];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
